package com.cl.short_video_java.web.common;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.*;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.domain.ExtUserInfo;
import com.alipay.api.domain.ExtendParams;
import com.alipay.api.domain.GoodsDetail;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cl.short_video_java.annotation.Log;
import com.cl.short_video_java.common.AliPayConfigInfo;
import com.cl.short_video_java.common.Result;
import com.cl.short_video_java.config.AliPayConfig;
import com.cl.short_video_java.exception.WebException;
import com.cl.short_video_java.menum.BusinessType;
import com.cl.short_video_java.pojo.VideoShop;
import com.cl.short_video_java.pojo.VideoShopOrder;
import com.cl.short_video_java.service.PayService;
import com.cl.short_video_java.service.SysSettingService;
import com.cl.short_video_java.service.VideoShopOrderService;
import com.cl.short_video_java.service.VideoShopService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author 付
 * @Date 2024-11-11 11:19
 * @Version 1.0
 * @description
 * @since 1.0
 */
@RestController
@Slf4j
@RequestMapping("/pay")
public class PayController {

	private PayService payService;
	private SysSettingService sysSettingService;
	private VideoShopOrderService videoShopOrderService;

	@Autowired
	PayController(PayService payService,
				  SysSettingService sysSettingService,
				  VideoShopOrderService videoShopOrderService) {
		this.payService = payService;
		this.sysSettingService = sysSettingService;
		this.videoShopOrderService = videoShopOrderService;
	}


	/**
	 * 支付宝支付
	 *
	 * @param shopId 商品id
	 * @return 表单
	 */
	@GetMapping("/alipay")
	public Result pay(@RequestParam("shopId") Integer shopId, HttpServletRequest request) {
		String formStr = payService.tradeCreate(shopId, request);
		if (formStr == null) {
			throw new WebException("订单创建失败");
		}
		return Result.success(formStr);
	}

	@PostMapping("/notify")
	public String notify(@RequestParam Map<String, String> params) {
		log.info("支付通知");
		log.info("通知参数======>" + params);
		String result = "failure";

		// 异步通知验签
		try {
			boolean b = AlipaySignature.rsaCheckV1(params,
					sysSettingService.getSysSettingByKey("alipay_public_key"),
					AlipayConstants.CHARSET_UTF8,
					AlipayConstants.SIGN_TYPE_RSA2);

			if (!b) {
				// 签名校验失败
				log.error("支付成功异步通知校验失败");
				return result;
			}
			log.info("支付成功异步通知校验成功");
			// 当前订单号是否为当前订单的订单号
			String tradeNo = params.get("out_trade_no");
			VideoShopOrder shopOrder = videoShopOrderService.getOne(new QueryWrapper<VideoShopOrder>().eq("order_id", tradeNo));
			if (shopOrder == null) {
				log.error("订单号校验失败");
				return result;
			}
			// 判断total_amount 是否为该订单的实际金额
			String amount = params.get("total_amount");
			BigDecimal bigDecimal = new BigDecimal(amount);
			if (!shopOrder.getPayPrice().equals(bigDecimal)) {
				log.error("金额校验失败");
				return result;
			}

			// 判断seller_id 是否为该订单的对应的操作方，也就是是否支付给了对应的商家
			String sellerId = params.get("seller_id");
			if (!sellerId.equals(sysSettingService.getSysSettingByKey("alipay_server_id"))) {
				log.error("商家校验失败");
				return result;
			}

			// 验证appid 是否为商户本身
			String appId = params.get("app_id");
			if (!appId.equals(sysSettingService.getSysSettingByKey("alipay_app_id"))) {
				log.error("appid校验失败");
				return result;
			}

			String tradeStatus = params.get("trade_status");
			if (!tradeStatus.equals("TRADE_SUCCESS")) {
				log.error("支付未成功");
				return result;
			}
			// TODO 处理业务 修改订单状态，记录支付日志
			videoShopOrderService.processOrder(params);
			result = "SUCCESS";
		} catch (AlipayApiException e) {
			throw new WebException(e.getMessage());
		}
		return result;
	}

	@PostMapping("/trade/cancel")
	public Result cancel(@RequestParam("OrderNo") String orderNo) {
		videoShopOrderService.cancel(orderNo);
		return Result.success();
	}

	@GetMapping("/query")
	public Result queryOrder(@RequestParam("orderNo") String orderNo) {
		String result = videoShopOrderService.queryOrder(orderNo);
		return Result.success();
	}
}